<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-tooltip/paper-tooltip.html">
<link rel="import" href="../../bower_components/paper-material/paper-material.html">
<link rel="import" href="../../bower_components/paper-progress/paper-progress.html">

<link rel="import" href="plan-selection-widget.html">
<link rel="import" href="card-form.html">

<dom-module id="cc-required">
    <template>
        <style include="shared-styles forms single-page">
            paper-material {
                display: block;
                padding: 24px;
                transition: all 0.2 ease-in;
            }
            paper-dialog#ccRequired {
                max-width: 400px;
            }
            .progress {
                position: relative;
                width: 100%;
                left: 0;
                right: 0;
                margin-left: -24px;
            }
            paper-progress#progresserror ::slotted(#primaryProgress),
                background-color: var(--red-color);
            }
            .errormsg-container {
                color: var(--red-color);
                width: 100%;
                padding-left: 20px;
                font-size: 14px;
            }
            .errormsg-container iron-icon {
                color: inherit;
                margin-right: 8px;
            }
            paper-progress {
                width: 100%;
                left: 0;
                right: 0;
            }
            .help {
                align-self: flex-end;
            }
            card-form {
                margin: 4px 0;
            }
            span#vcpus, span#datapoints, span#rulechecks, span#apirequests, span#retention {
                border-bottom: 1px dashed #999;
            }
            .free {
                line-height: 1.8em;
                margin-top: 0;
            }
            paper-tooltip {
                font-size: 14px;
            }
            div.prepaid {
                margin-top: 8px;
            }
            .info-icon {
                width: 16px;
                height: 16px;
                vertical-align: text-bottom;
            }
            .buttons {
                padding: 8px 19px 24px 24px !important;
            }
        </style>

        <paper-dialog id="ccRequired" with-backdrop modal>
            <h2><span hidden$="[[title]]">Credit card required</span>[[title]]</h2>
            <paper-dialog-scrollable>
                <p class="free" hidden$="[[plan]]"><strong>Free Trial of 14 days.</strong> Pay as you go rates will apply after free trial period ends. <a href="/my-account/billing"><iron-icon class="info-icon" icon="icons:info"></iron-icon></a>
                </p>
                <p hidden$="[[!plan]]">
                    <strong>[[plan]] Plan</strong><br/>
                    <a class="regular blue-link" href="/my-account/billing" dialog-dismiss>Other plans</a> also available.
                </p>
                <card-form id="inAddCloud" card-valid="{{cardValid}}" token="[[token]]"></card-form>
            </paper-dialog-scrollable>
            <div class="progress" hidden$="[[!showProgress]]">
                <paper-progress id="progress" indeterminate hidden$="[[!loading]]"></paper-progress>
                <paper-progress id="progresserror" value="100" hidden$="[[!formError]]"></paper-progress>
                <hr class="appform"/>
                <p class="errormsg-container" hidden$="[[!formError]]"><iron-icon icon="icons:error-outline"></iron-icon><span id="errormsg">[[cardErrors]]</span></p>
            </div>
            <div class="buttons">
                <paper-button on-tap="_goBack" hidden$="[[!hasBack]]">Back</paper-button>
                <paper-button on-tap="_cancel" dialog-dismiss hidden$="[[!hasCancel]]">Cancel</paper-button>
                <paper-button class="blue" disabled$="[[!cardValid]]" on-tap="_submitCard">Subscribe</paper-button>
            </div>
        </paper-dialog>

        <iron-ajax id="addCard" url="/api/v1/billing" method="POST" loading="{{loading}}" handle-as="xml" on-response="_handleCardResponse" on-error="_handleCardError"></iron-ajax>

    </template>
    <script>
        (function() {
            'use strict';

            Polymer({
                is: 'cc-required',

                properties: {
                    cardValid: {
                        type: Boolean,
                        value: false
                    },
                    formError: {
                        type: Boolean,
                        value: false
                    },
                    cardErrors: {
                        type: String
                    },
                    loading: {
                        type: Boolean,
                        value: false
                    },
                    plan: {
                        type: String,
                        value: false,
                        notify: true
                    },
                    planObject: {
                        type: Object,
                        computed: '_computePlanObject(plan)'
                    },
                    showProgress: {
                        type: Boolean,
                        value: false,
                        computed: '_computeShowProgress(formError,loading)'
                    },
                    hasCancel: {
                        type: Boolean,
                        value: false
                    },
                    hasBack: {
                        type: Boolean,
                        value: false
                    },
                    title: {
                        type: String
                    }
                },
                listeners: {
                    'open-cc-required': 'open',
                    'close-cc-required': 'close',
                    'card-response': '_gotCardResponse',
                    'refit': '_refit'
                },
                attached: function() {
                },
                _refit: function(e){
                    this.$.ccRequired.refit();
                },
                open: function() {
                    this._clearErrors();
                    this.$.ccRequired.open();
                },
                close: function() {
                    this.$.ccRequired.close();
                    this.shadowRoot.querySelector('card-form#inAddCloud').reset();
                    this._clearErrors();
                },
                _submitCard: function(e){
                    this._clearErrors();
                    if (this.cardValid) {
                        this.shadowRoot.querySelector('card-form#inAddCloud').verify();
                    }
                },
                _gotCardResponse: function(e){
                    if (this.cardValid) {
                        var card = this.shadowRoot.querySelector('card-form#inAddCloud');
                        if (e.detail.token) {
                            var payload = {token: e.detail.token};
                            if (this.plan)
                                payload.plan = this.plan;
                            this.$.addCard.headers["Content-Type"] = 'application/json';
                            this.$.addCard.headers["Csrf-Token"] = CSRF_TOKEN;
                            this.$.addCard.body = payload;
                            this.$.addCard.generateRequest();
                        }
                        else if (card.errors) {
                            this.set('formError', true);
                            this.set('cardErrors', card.errors);
                        }
                        else {
                            this.set('loading', true)
                        }
                    }
                    this.$.ccRequired.refit();
                },
                _handleCardResponse: function(e){
                    this.dispatchEvent(new CustomEvent('close-cc-required'));

                    this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {msg:'Successfull subscription. Welcome onboard!', duration: 3000} }));

                },
                _handleCardError: function(e){;
                    this.set('cardErrors', e.detail.request.xhr.responseText);
                    this.set('formError', true);
                },
                _computeShowProgress: function(formError,loading){
                    return this.formError || this.loading;
                },
                _clearErrors: function(){
                    this.set('formError', false);
                    this.set('cardErrors', '');
                },
                _cloudAddAjaxResponse: function(response) {
                    this._unsetProvider();
                    this.dispatchEvent(new CustomEvent('go-to', { bubbles: true, composed: true, detail:  {url: '/'} }));
                    this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {msg:'Cloud added successfully!',duration:3000} }));

                },
                _cloudAddAjaxError: function(response) {
                    console.error('add-cloud error', response);
                },
                _computePlanObject: function(plan){
                    if (!plan)
                        return {};
                    else {
                        // TODO get plan object from org
                    }
                },
                _goBack: function(e) {
                    e.stopImmediatePropagation();
                    if (history)
                        history.back();
                    else
                        this.dispatchEvent(new CustomEvent('go-to', { bubbles: true, composed: true, detail: '/' }));

                },
                _cancel: function(e) {
                    this.close();
                }
            });
        })();
    </script>
</dom-module>